const Role = require('../db/model/Role/Role')
const {Op} = require('sequelize')

const getRoleList = async ({name, isSchool, description, pageIndex, pageSize, createTime}) => {
  const where = {
    name: {
      [Op.substring]: name
    },
    description: {
      [Op.substring]: description
    }
  }

  if (isSchool!==undefined) {
    where.isSchool = isSchool
  }

  if (createTime.length) {
    where[`created_at`] = {
      [Op.gte]: createTime[0],
      [Op.lte]: createTime[1]
    }
  }

  const result = await Role.findAndCountAll({
    limit: +pageSize,
    offset: pageSize * pageIndex,
    order: [
      [ 'id', 'desc' ]
    ],
    where
  })

  return {
    count: result.count,
    data: result.rows
  }
}

const getRoleOne = async (id) => {
  const result = await Role.findOne({
    where: {
      id
    }
  })

  return result.dataValues
}

const createRole = async ({name, auth, isSchool, description}) => {
  const result = await Role.create({
    name,
    auth,
    isSchool,
    description
  })

  const data = result.dataValues

  return data
}

const updateRole = async ({name, auth, isSchool, description, id}) => {
  const whereOpt = {
    id
  }
  const result = await Role.update({
    name,
    auth,
    isSchool,
    description
  }, {
    where: whereOpt
  })

  const data = result.length > 0

  return data
}

const delRole = async (id) => {
  const result = await Role.destroy({
    where: {
      id
    }
  })

  return result > 0
}

const getRoleListAll=async ()=>{
  const result = await Role.findAll()

  const data = result.map(item => item.dataValues)

  return data
}

module.exports = {
  createRole,
  delRole,
  getRoleList,
  getRoleOne,
  updateRole,
  getRoleListAll
}
